﻿using CodeCarvings.Piczard;
using CodeCarvings.Piczard.Filters.Watermarks;
using HPIT.RentHouse.Admin.Models;
using HPIT.RentHouse.Common;
using HPIT.RentHouse.DTO;
using HPIT.RentHouse.IService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HPIT.RentHouse.Admin.Controllers
{
    [Authorize]
    public class HouseController : Controller
    {
        private readonly IHouseService _houseService;
        private readonly IRegionService _regionService;
        private readonly IIdNamesService _idNamesService;
        private readonly ICommunityService _communityService;

        public HouseController(IHouseService houseService, IRegionService regionService,IIdNamesService idNamesService,ICommunityService communityService)
        {
            _houseService = houseService;
            _regionService = regionService;
            _idNamesService = idNamesService;
            _communityService = communityService;
        }

        public ActionResult Index(int typeId)
        {
            ViewBag.typeId = typeId;
            return View();
        }

        /// <summary>
        /// 获取房源分页数据
        /// </summary>
        /// <param name="communityName"></param>
        /// <param name="typeId"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetHouseList(string communityName, int typeId, int start, int length)
        {
            int count = 0;
            var list = _houseService.GetHouseList(communityName, typeId, start, length, ref count);
            PageModel pageModel = new PageModel();
            pageModel.data = list;
            pageModel.recordsTotal = count;
            pageModel.recordsFiltered = count;
            return Json(pageModel);
        }

        public ActionResult Create()
        {
            MyFormsPrincipal<LoginAdminDTO> user = User as MyFormsPrincipal<LoginAdminDTO>;
            //区域
            ViewBag.RegionList = _regionService.GetList(user.UserData.CityId).Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() }).ToList();

            //房型
            ViewBag.RoomTypeList=_idNamesService.GetList(IdNameEnum.户型.ToString()).Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() }).ToList();

            //状态
            ViewBag.StatusList= _idNamesService.GetList(IdNameEnum.房屋状态.ToString()).Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() }).ToList();

            //装修
            ViewBag.DecorateStatusList= _idNamesService.GetList(IdNameEnum.装修状态.ToString()).Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() }).ToList();

            //类别
            ViewBag.TypeList= _idNamesService.GetList(IdNameEnum.房屋类型.ToString()).Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() }).ToList();

            //房源附属设施
            List<AttachmentDTO> list= _houseService.GetHouseAttachments();
            return View(list);
        }

        /// <summary>
        /// 获取小区信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetCommunities(long regionId)
        {
            List<CommuityDTO> list= _communityService.GetList(regionId);
            return Json(list);
        }

        /// <summary>
        /// 提交添加房源表单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(HouseAddDTO dto)
        {
            AjaxResult result = _houseService.AddHouse(dto);
            return Json(result);
        }

        /// <summary>
        /// 编辑房源信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(long id)
        {

            //获取当前登录管理员的信息，根据当前管理所管辖的地区，来获取对应的区域
            var currentAdmin = User as MyFormsPrincipal<LoginAdminDTO>;

            //根据CityId获取当前所在的区域
            ViewBag.RegionList = _regionService.GetList(currentAdmin.UserData.CityId).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() });

            //房型
            ViewBag.RoomTypeList = _idNamesService.GetList(IdNameEnum.户型.ToString()).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() });

            //装修类型
            ViewBag.DecorateStatusList = _idNamesService.GetList(IdNameEnum.装修状态.ToString()).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() });

            //状态
            ViewBag.StatusList = _idNamesService.GetList(IdNameEnum.房屋状态.ToString()).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() });

            //类型
            ViewBag.TypeList = _idNamesService.GetList(IdNameEnum.房屋类型.ToString()).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() });

            //房源设施
            ViewBag.AttachmentList = _houseService.GetHouseAttachments();


            var dto = _houseService.GetHouse(id);

            //获取当前房源所在区域的小区
            ViewBag.CommunityList = _communityService.GetList(dto.RegionId).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() });

            return View(dto);
        }

        /// <summary>
        /// 提交编辑房源信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(HouseEditDTO dto)
        {
            var result = _houseService.EditHouse(dto);
            return Json(result);
        }

        public ActionResult UploadPic(long houseId)
        {
            ViewBag.houseId = houseId;
            return View();
        }

        public ActionResult ToUploadPic(int houseId, HttpPostedFileBase file)
        {
            //month月，minute
            string md5 = CommonHelper.CalcMD5(file.InputStream);
            string ext = Path.GetExtension(file.FileName);
            string path = "/upload/house/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + ext;// /upload/2017/07/07/afadsfa.jpg
            string thumbPath = "/upload/house/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + "_thumb" + ext;
            string fullPath = HttpContext.Server.MapPath("~" + path);//d://22/upload/2017/07/07/afadsfa.jpg
            string thumbFullPath = HttpContext.Server.MapPath("~" + thumbPath);
            new FileInfo(fullPath).Directory.Create();//尝试创建可能不存在的文件夹

            file.InputStream.Position = 0;//指针复位
                                          //file.SaveAs(fullPath);//SaveAs("d:/1.jpg");
                                          //缩略图
            ImageProcessingJob jobThumb = new ImageProcessingJob();
            jobThumb.Filters.Add(new FixedResizeConstraint(200, 200));//缩略图尺寸200*200
            jobThumb.SaveProcessedImageToFileSystem(file.InputStream, thumbFullPath);

            file.InputStream.Position = 0;//指针复位

            //水印
            ImageWatermark imgWatermark = new ImageWatermark(HttpContext.Server.MapPath("~/images/watermark.jpg"));
            imgWatermark.ContentAlignment = System.Drawing.ContentAlignment.BottomRight;//水印位置
            imgWatermark.Alpha = 50;//透明度，需要水印图片是背景透明的png图片
            ImageProcessingJob jobNormal = new ImageProcessingJob();
            jobNormal.Filters.Add(imgWatermark);//添加水印
            jobNormal.Filters.Add(new FixedResizeConstraint(600, 600));
            jobNormal.SaveProcessedImageToFileSystem(file.InputStream, fullPath);

            AjaxResult result= _houseService.AddHousePics(new HousePicDTO { HouseId = houseId, Url = path, ThumbUrl = thumbPath });
            return Json(result);
        }


    }
}